import json

from django.core.cache import cache
from django.core.paginator import Paginator
from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from homes.models import Area, House, HouseImage
from ihome.utils.mixins import LoginRequiredMixin

from ihome.utils.qiniuyun.qiniu_storage import storage

from ihome.utils import constants

from ihome.utils.constants import QINIU_DOMIN_PREFIX


class SubAreasView(View):
    def get(self, request):
        """城区列表"""
        try:
            subs_li = Area.objects.all()

        except Exception as e:
            return JsonResponse({'code': 400,
                                 'message': '获取错误'})

        sub_li = []
        try:
            for res in subs_li:
                sub_li.append({
                    "aid": res.id,
                    "aname": res.name,
                })
        except Exception as e:
            return JsonResponse({
                'code': 400,
                'message': '信息获取错误'
            })

        # ② 组织数据并返回
        return JsonResponse({"errno": "0",
                             "errmsg": "获取成功",
                             'data': sub_li})


class ReleaseHousing(LoginRequiredMixin ,View):

    def post(self, request):
        """发布房源"""
        # 获取参数并进行校验
        req_data = json.loads(request.body.decode())
        title = req_data.get('title')
        price = req_data.get('price')
        area_id = req_data.get('area_id')
        address = req_data.get('address')
        room_count = req_data.get('room_count')
        acreage = req_data.get('acreage')
        unit = req_data.get('unit')
        capacity = req_data.get('capacity')
        beds = req_data.get('beds')
        deposit = req_data.get('deposit')
        min_days = req_data.get('min_days')
        max_days = req_data.get('max_days')
        facility = req_data.get('facility')

        if not all([title, price, area_id, address, room_count, acreage, unit, capacity, beds, deposit, min_days,
                    max_days, facility]):
            return JsonResponse({'code': "400",
                                 'message': '缺少必传参数'})


        try:
            price = int(float(price) * 100)
        except Exception as e:
            return JsonResponse({'code': "400",
                                 'message': '参数错误'})


        try:
            house = House.objects.create(title=title,
                                         area_id=area_id,
                                         address=address,
                                         room_count=room_count,
                                         acreage=acreage,
                                         unit=unit,
                                         capacity=capacity,
                                         beds=beds,
                                         deposit=deposit,
                                         min_days=min_days,
                                         max_days=max_days,
                                         # user_id = request.user.id
                                         user_id=request.user.id
                                         )
            house.facility.add(*facility)
            house.save()
        except Exception as e:
            return JsonResponse({'code': "400",
                                 'message': '数据库保存错误'})

        data = {}
        data['house_id'] = house.id

        return JsonResponse({
            "errno": "0",
            "errmsg": "发布成功",
            "data": data,
        })

    def get(self, request):
        aid = request.GET.get('aid')
        sd = request.GET.get('sd')
        ed = request.GET.get('ed')
        sk = request.GET.get('sk')
        p = request.GET.get('p')

        """
        10 2020-11-15 2020-11-20 new 1
        <class 'str'> <class 'str'> <class 'str'> <class 'str'> <class 'str'>
        """
        sd_int = int(sd.replace('-', ''))
        ed_int = int(ed.replace('-', ''))
        p_int = int(p)

        days = ed_int - sd_int

        houses = House.objects.filter(Q(min_days__lt=days) & Q(area_id=aid))

        paginator = Paginator(houses, 3)
        results = paginator.get_page(p_int)

        houses_list = []
        for house in results:

            # if house.max_days == '0' and int(house.max_days) > days:
            img_url = QINIU_DOMIN_PREFIX + str(house.index_image_url)
            user_avatar = QINIU_DOMIN_PREFIX + str(house.user.avatar)

            houses_list.append({"address": house.address,
                                "area_name": house.area.name,
                                "ctime": house.create_time,
                                "house_id": house.id,
                                "img_url": img_url,
                                "order_count": house.order_count,
                                "price": house.price,
                                "title": house.title,
                                "user_avatar": user_avatar})
            data = {"houses": houses_list,
                    "total_page": paginator.num_pages}

        return JsonResponse({"data": data,
                             "errmsg": "请求成功",
                             "errno": 0})


class HouseListView(LoginRequiredMixin, View):

    def get(self, request):
        houses = House.objects.filter(user_id=request.user.id)
        houses_list = []
        http = "http://qjq2idd98.hd-bkt.clouddn.com/"
        for house in houses:

            img_url = http + house.index_image_url
            user_avatar = http + str(house.user.avatar)

            houses_list.append({"area_name": house.area.name,
                                "ctime": house.create_time,
                                "house_id": house.id,
                                "img_url": img_url,
                                "order_count": house.order_count,
                                "price": house.price,
                                "room_count": house.room_count,
                                "title": house.title,
                                "user_avatar": user_avatar
                                })

        return JsonResponse({"data": {"houses": houses_list},
                             "errmsg": "ok",
                             "errno": 0
        })


class Hose_Sourse_View(LoginRequiredMixin, View):

    def post(self, request, house_id):
        # 提取参数
        image_file = request.FILES.get('house_image', None)

        if image_file is None:
            return JsonResponse({
                "errno": 400,
                "errmsg": "图片没有输入，不能上传"
            }, status=400)

        image_data = image_file.read()

        try:
            file_name = storage(image_data)

        except Exception as e:
            return JsonResponse({
                "code": 400,
                "errmsg": "图片上传失败"
            })

        try:
            print(house_id)
            house = House.objects.get(pk=house_id)
            house.index_image_url = file_name
            house.save()

        except Exception as e:
            print(e)
            return JsonResponse({
                "code": 400,
                "errmsg": "图片保存失败"
            })

        url = constants.QINIU_DOMIN_PREFIX + file_name
        return JsonResponse({
            "data": {
                "url": url
            },
            "errno": "0",
            "errmsg": "图片上传成功",
        })


# /api/v1.0/houses/index
class HouseShowView(View):
    def get(self, request):
        """首页房屋推荐"""
        data = []

        houses = House.objects.all()
        paginator = Paginator(houses, 3)
        results = paginator.get_page(1)

        for house in results:
            data.append({
                'house_id': house.id,
                "img_url": "http://qjq2idd98.hd-bkt.clouddn.com/" + house.index_image_url,
                "title": house.title
            })
        return JsonResponse({
            "data": data,
            "errmsg": "OK",
            "errno": "0"
        })


# /api/v1.0/houses/[int:house_id]
class HouseDetaView(View):
    def get(self, request, house_id):
        try:
            house = House.objects.get(id = house_id)
            facilities = []
            for facility in house.facility.all():
                facilities.append(facility.id)

            orders = house.order_set.all()
            comments = []
            for order in orders:
                comments.append({
                    'comment': order.comment,
                    'ctime': order.create_time,
                    'username': order.user.username,
                })

            img_urls = []
            house_image = HouseImage.objects.filter(house_id = house_id)
            print(len(house_image))
            for img in house_image:
                img_urls.append(QINIU_DOMIN_PREFIX + str(img.url))
        except Exception as e:
            return JsonResponse({
                'errmsg': '请求失败',
                'errno': '400'
            })
        print('88888888')
        return JsonResponse({
            'data': {
                'house': {
                    "acreage": house.acreage,
                    "address": house.address,
                    "beds": house.beds,
                    "capacity": house.capacity,
                    'comments': comments,
                    'deposit': house.deposit,
                    "facilities": facilities,
                    'hid': house.id,
                    'img_urls': img_urls,
                    'max_days': house.max_days,
                    'min_days': house.min_days,
                    'price': house.price,
                    'room_count': house.room_count,
                    'title': house.title,
                    'unit': house.unit,
                    'user_avatar': QINIU_DOMIN_PREFIX + str(house.user.avatar),
                    'user_id': house.user.id,
                    'user_name': house.user.username
                },
                'user_id': house.user.id
            },
            'errmsg': 'OK',
            'errno': '0'
        })


